import Vue from 'vue'
import store from "../store"
import axios from 'axios'
import qs from 'qs'
import md5 from './md5'




/** 设置各需地址 m1,m2,ml3，m4,xxh,gudi */
// let url = "http://192.168.0.81/"
/** 配置请求信息 */
axios.interceptors.request.use(config => {
	return config
}, error => {
	return Promise.reject(error);
})

axios.interceptors.response.use(response => {
	return response
}, error => {
	return Promise.resolve(error.response)
})

axios.defaults.baseURL = url + 'Api';
Vue.prototype.axios = axios;

var url;
export function httpServer(opts, data) {
	var getLoginPeriod = store.state.loginPeriodId;
	if (getLoginPeriod == 1 || getLoginPeriod == 2 || getLoginPeriod == 4) {
		url = 'https://m' + store.state.loginPeriodId + '.maoqio.com/'
	} else {
		if (getLoginPeriod == 3) {
			url = 'https://ml' + store.state.loginPeriodId + '.maoqio.com/'
		} else if (getLoginPeriod == 5) {
			url = 'https://gudi.maoqio.com/'
		} else if (getLoginPeriod == 6) {
			url = 'https://xxh.maoqio.com/'
		}
	}
	
	/**********************************************************分割线************************************************/

	let Public = { //公共参数
		'sign': md5(Date.parse(new Date()) + '2y92rfa969y4hyjrwuqjygog3zcu50l3'),
		'timestamp': Date.parse(new Date()),
	}
	let needtoken = {
		token: wx.getStorageSync(" user_token"),
		user_id: wx.getStorageSync(" user_id")
	}
	let httpDefaultOpts = { //http默认配置
		method: opts.method,
		baseURL: url + 'Api/',
		url: opts.url,
		timeout: 30000,
		headers: {
			"Content-Type": "application/x-www-form-urlencoded",
			"Authorization": Public.sign + " " + Public.timestamp + " " + (needtoken._token || "")
		},
		params: data,
		data: qs.stringify(data),
	}
	console.log(data);
	if (opts.method == 'get') {
		delete httpDefaultOpts.data
	} else {
		delete httpDefaultOpts.params
	}
	let promise = new Promise(function (resolve, reject) {
		axios(httpDefaultOpts).then(
			(res) => {
				resolve(res);
			}
		).catch(
			(response) => {
				// 如果http状态码正常，则直接返回数据
				if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
					return response
					// 如果不需要除了data之外的数据，可以直接 return response.data
				} else {
				}
				reject(response)
			}
		)
	})
	return promise
}

/*开启路由验证*/
// router.beforeEach((to, from, next) => {
// 	if (to.meta.requireAuth){  // 判断该路由是否需要登录权限
// 		if (localStorage.getItem("isLogin")=="1") {  // 判断当前的token是否存在
// 			next();
// 		}
// 		else {
// 		next({
// 			path: '/login?role=' + getUrlCode(),
// 			query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
// 		})
// 		}
// 		next();
// 	}
// 	else {
// 			next();
// 	}
// 	window.scrollTo(0,0);
// 	Promise.resolve().then(()=>{
// 		url:global.location.href
// 	})
// });